<script setup>
import { ref, watch, reactive } from 'vue'
import { useWorkerStore } from '@/stores/woker'
import { ElNotification } from 'element-plus'

const workerStore = useWorkerStore()
const curPage = ref(1)
const pageSize = ref(10)
const selArr = ref([])
workerStore.getWorkData(curPage.value, pageSize.value)
const handleSizeChange = (size) => {
  pageSize.value = size
}
const handleCurrentChange = (page) => {
  curPage.value = page
}

const handleSelectionChange = (list) => {
  selArr.value = list
}

const filterGender = (value, row, column) => {
  const property = column['property']
  return row[property] == value
}

const fd = ref({})
const centerDialogVisible = ref(false)
const edit = (data) => {
  centerDialogVisible.value = true
  fd.value = { ...data }
}
const reset = () => {
  centerDialogVisible.value = false
  fd.value = {}
}
const form = ref()
const rules = reactive({
  name: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('姓名不能为空'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  age: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('年龄不能为空'))
        } else if (/^[1-9]*\d{1}$/.test(value)) callback()
        else callback(new Error('年龄只能在1-99岁之间'))
      },
      trigger: 'blur'
    }
  ],
  gender: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('性别不能为空'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})
const submit = async () => {
  await form.value.validate()
  fd.value.updated_at = new Date().toLocaleString()
  workerStore.editWorker(fd.value)
  centerDialogVisible.value = false
  workerStore.getWorkData(curPage.value, pageSize.value)
}

const remove = (data) => {
  ElNotification.closeAll()
  if (Array.isArray(data)) {
    if (data.length)
      ElMessageBox.confirm('您确定要删除选中的人员吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        workerStore.delData(data)
        workerStore.getWorkData(curPage.value, pageSize.value)
        ElNotification({
          title: '删除成功',
          type: 'success'
        })
      })
    else
      ElNotification({
        title: '未选中人员',
        type: 'error'
      })
  } else if (data == 'all') {
    ElMessageBox.confirm('您确定要清空数据吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      workerStore.delData(data)
      workerStore.getWorkData(curPage.value, pageSize.value)
      ElNotification({
        title: '删除成功',
        type: 'success'
      })
    })
  } else {
    ElMessageBox.confirm(`您确定要删除${data.name}吗?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      workerStore.delData(data)
      workerStore.getWorkData(curPage.value, pageSize.value)
      ElNotification({
        title: '删除成功',
        type: 'success'
      })
    })
  }
}

watch(
  () => [curPage.value, pageSize.value],
  ([newCurPage, newPageSize]) => {
    workerStore.getWorkData(newCurPage, newPageSize)
  },
  {
    deep: true
  }
)
</script>

<template>
  <div class="container">
    <div>
      <el-table
        v-loading="workerStore.loading"
        :data="workerStore.workerData"
        @selection-change="handleSelectionChange"
        height="70vh"
        stripe
        style="width: 100%"
      >
        <el-table-column align="center" prop="isSelect" type="selection">
        </el-table-column>
        <el-table-column align="center" prop="name" label="姓名" />
        <el-table-column
          align="center"
          width="100px"
          prop="age"
          sortable
          label="年龄"
        />
        <el-table-column
          align="center"
          prop="gender"
          width="100px"
          :filters="[
            { text: '男', value: 1 },
            { text: '女', value: 0 }
          ]"
          :filter-method="filterGender"
          label="性别"
        >
          <template #default="{ row }">
            {{ row.gender == 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="创建时间">
          <template #default="{ row }">
            {{ new Date(row.created_at).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="updated_at" label="更新时间">
          <template #default="{ row }">
            {{ new Date(row.updated_at).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" :fixed="false">
          <template #default="{ row }">
            <el-button @click="edit(row)" plain type="primary">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button @click="remove(row)" plain type="danger">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-button type="warning" @click="remove(selArr)" plain>
          删除
        </el-button>
        <el-button type="danger" @click="remove('all')" plain>
          清空所有数据
        </el-button>
      </div>
    </div>
    <el-pagination
      v-model:current-page="curPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 20, 50, 100]"
      :small="false"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="workerStore.workerList.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-left: auto"
    />
    <el-dialog
      v-model="centerDialogVisible"
      title="添加人员名单"
      width="500"
      align-center
    >
      <el-form
        ref="form"
        :rules="rules"
        label-width="auto"
        :model="fd"
        style="max-width: 600px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="fd.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="fd.age" />
        </el-form-item>
        <el-form-item label="性别 " prop="gender">
          <el-select
            v-model="fd.gender"
            placeholder=""
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in [
                { value: '1', label: '男' },
                { value: '0', label: '女' }
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reset">取消</el-button>
          <el-button type="primary" @click="submit"> 编辑 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
</style>
